package com.test.multithread;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;

/**
 * Created by jl on 2016/8/7.
 */
public class ReadThread extends Thread {
    //定义字节数组（取水的竹筒）的长度
    private final int BUFF_LEN = 256;
    //定义读取的起始点
    private long start;
    //定义读取的结束点
    private long end;
    //将读取到的字节输出到raf中  randomAccessFile可以理解为文件流，即文件中提取指定的一部分的包装对象
    private RandomAccessFile raf;
    //线程中需要指定的关键字
    private String keywords;
    //此线程读到关键字的次数
    private int curCount = 0;
    private CountDownLatch doneSignal;

    public ReadThread(long start, long end, RandomAccessFile raf,String keywords,CountDownLatch doneSignal){
        this.start = start;
        this.end = end;
        this.raf  = raf;
        this.keywords = keywords;
        this.doneSignal = doneSignal;
    }

    public void run() {
        try {
            raf.seek(start);
            long contentLen = end - start;
            long times = contentLen / BUFF_LEN + 1;
            System.out.println(this.toString() + "需读取的次数：" + times);
            byte[] buff = new byte[BUFF_LEN];
            byte[] leftBuff = new byte[(int) (contentLen % BUFF_LEN)];
            int hasRead = 0;
            String result;
            System.out.println(this.toString() + "------读取的内容开始------");
            long t1 = System.currentTimeMillis();
            for(int i=0;i<times;i++) {
                if (i == times - 1) {
                    hasRead = raf.read(leftBuff);
                }else {
                    hasRead = raf.read(buff);
                }
                if (hasRead < 0) {
                    break;
                }
                result = new String(buff, "gb2312");
            }
            System.out.println(this.toString() + "------读取的内容结束------");
            System.out.println(this.toString() + "耗时：" + (System.currentTimeMillis() - t1) + "ms");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            doneSignal.countDown();
        }

    }
}
